package com.dyna.gateway.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.dyna.constants.RedisKeyConstant;
import com.dyna.constants.StringPool;
import com.dyna.constants.TokenConstant;
import com.dyna.core.exception.CaptchaException;
import com.dyna.core.utils.VerifyCodeUtil;
import com.dyna.domain.resp.R;
import com.dyna.gateway.service.ValidateCodeService;
import com.dyna.utils.RdsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author admin
 */
@Slf4j
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Override
    public R<Object> createCaptcha() {
        // 生成随机字串
        String verifyCode = VerifyCodeUtil.createCode();
        log.info("获取登录验证码:::【{}】", verifyCode);
        // 唯一标识
        String uuid = IdUtil.fastSimpleUUID();
        String verifyKey = RedisKeyConstant.CAPTCHA_PRE_KEY + uuid;
        String verifyValue = verifyCode + StringPool.DASH + System.currentTimeMillis();

        RdsUtil.set(verifyKey, verifyValue, TokenConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            VerifyCodeUtil.outputImage(w, h, stream, verifyCode);
            Map<String, String> dataMap = new HashMap<>(4);
            dataMap.put("uuid", uuid);
            dataMap.put("img", "data:image/png;base64," + Base64.encode(stream.toByteArray()));
            return R.data(dataMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @Override
    public void checkCaptcha(String key, String value) throws CaptchaException {

    }

    @Override
    public R<Object> createQrCode() {
        return R.data("生成二维码");
    }

}